﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LoanCalculator.Core.Classes
{
    [Serializable]
    public class Amortization : Loan
    {

        public Amortization(double loanAmount,
                            double annualInterestRate,
                            double months,
                            double downPayment,
                            double propertyTax,
                            double propertyInsurance)
        {
            LoanAmount = loanAmount;
            AnnualInterestRate = annualInterestRate;
            Months = months;
            DownPayment = downPayment;
            PropertyTax = propertyTax;
            PropertyInsurance = propertyInsurance;
        }

        public IList<Payments> GetAmortizationPayments()
        {
            IList<Payments> payments = new List<Payments>();
            double amount = LoanAmount;
            double months = Months;
            double rate = AnnualInterestRate;
            double monthly = 0.0d;
            double payment = 0.0d;
            double total = 0.0d;
            double interest = 0.0d;

            double downpayment = DownPayment;
            double propertytax = PropertyTax;
            double propertyinsurance = PropertyInsurance;

            rate = (rate / 100);
            monthly = (rate / 12);

            payment =
                (amount - downpayment) *
                (Math.Pow((1 + monthly), months) * rate) /
                (12 * (Math.Pow((1 + monthly), months) - 1));

            payment += ((propertytax + propertyinsurance) / 12);

            total = (payment * months);
            interest = (total - amount);

            StringBuilder output = new StringBuilder();

            double _principal = 0.0d;
            double _interest = 0.0d;
            double _reduction = 0.0d;

            _principal = amount;

            for (int m = 1; m <= months; m++)
            {
                _interest = (monthly * _principal);
                _reduction = (payment - _interest);
                _principal = (_principal - _reduction);

                Payments pmt = new Payments { Month = m, 
                                                Payment = Math.Round(payment, 2), 
                                                Interest = Math.Round(_interest, 2), 
                                                Reduction = Math.Round(_reduction, 2),
                                                Principle = Math.Round(_principal, 2)
                };
                payments.Add(pmt);
            }
            return payments;
        }
    }
}
